package com.mjk.common.tools.xml.conver.impl;

import com.google.gson.internal.LinkedTreeMap;
import com.mjk.common.util.ObjectUtils;
import com.thoughtworks.xstream.converters.Converter;
import com.thoughtworks.xstream.converters.MarshallingContext;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import org.apache.commons.collections4.map.LinkedMap;

import java.util.LinkedHashMap;
import java.util.Map;

public class LinkedHashMapConverter implements Converter {


    @Override
    public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
        if (source instanceof LinkedHashMap) {
            LinkedHashMap<?, ?> map = (LinkedHashMap<?, ?>) source;
            for (Map.Entry<?, ?> entry : map.entrySet()) {
                Object key = entry.getKey();
                Object value = entry.getValue();
                writer.startNode(key.toString());
                if (value != null) {
                    writer.setValue(value.toString());
                } else {
                    writer.setValue("");
                }
                writer.endNode();
            }
        }
    }

    @Override
    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
        LinkedHashMap<Object, Object> map = new LinkedHashMap<>();
        while (reader.hasMoreChildren()) {
            reader.moveDown();
            String key = reader.getNodeName();
            String value = reader.getValue();
            map.put(key, value);
            reader.moveUp();
        }
        return map;
    }

    @Override
    public boolean canConvert(Class type) {
        return type.equals(LinkedHashMap.class);
    }
}
